package topic

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	"fmt"
	"google.golang.org/grpc/codes"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserGetTopicLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserGetTopicLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserGetTopicLogic {
	return &UserGetTopicLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserGetTopicLogic) UserGetTopic(req *types.TopicReq) (*types.TopicRsp, error) {
	var resp types.TopicRsp

	// 查询话题列表，包含统计信息
	topicQuery := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityTopic{}).
		Joins("topic").
		Joins("LEFT JOIN cs_community_post post ON post.topic_id = topic.id AND post.status = ?", types.PostTypeShelved). // 只统计已上架的帖子
		Where("topic.id = ?", req.Id).
		Select(
			"topic.id", "topic.name", "topic.image_url", "topic.description",
			fmt.Sprintf("CASE WHEN topic.type = %d THEN 1 END disabled", types.TopicTypeForbidden),
			"topic.menu_id", "topic.type",
			"IFNULL(COUNT(DISTINCT post.id), 0) as post_count",
			"IFNULL(SUM(post.view_count), 0) as view_count",
		)

	if err := topicQuery.
		Group("topic.id").
		Order("topic.id ASC").
		Offset((req.PageNum - 1) * req.PageSize).
		Limit(req.PageSize).
		Find(&resp).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	return &resp, nil
}
